﻿using NLog.Filters;
using NPOI.HPSF;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mbs.Utils
{
    public class ImageConvert
    {
        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ConvertToBase64(string path)
        {
            try
            {
                FileStream filestream = new FileStream(path, FileMode.Open);
                byte[] arr = new byte[filestream.Length];
                filestream.Read(arr, 0, (int)filestream.Length);
                string baser64 = Convert.ToBase64String(arr);
                filestream.Close();
                return baser64;
            }
            catch (Exception)
            {
                return "";
            }
        }
        /// <summary>
        /// base64转图片
        /// </summary>
        /// <param name="base64"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public static bool Base64ToFile(string base64, string savePath)
        {
            //System.AppDomain.CurrentDomain.BaseDirectory

            string fileFullPath = Path.GetDirectoryName(savePath);
            try
            {
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }
                string strbase64 = base64.Trim().Substring(base64.IndexOf(",") + 1);   //将‘，’以前的多余字符串删除
                using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64)))
                {
                    FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
                    byte[] b = stream.ToArray();
                    fs.Write(b, 0, b.Length);
                    fs.Close();
                    return true;
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}
